<?php
namespace Miniprogram\Controller;
use Think\Controller;
class BaiduController extends Controller {
    //百度小程序
    public $appid='22290847';
    public $secret='IzY9h91EEfo4WPfAUVdgtCo1oTMRynQI';
    public $key='cLZaputiWn1Bgkom6XVgEIeO49HHLHjf';
    public $accesstoken='';
    public $appKey = 'MMUwsg';//百度支付
    public $dealId = '1090921561';//百度支付
    //openssl生成证书
    // public $private_key='MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKbRkVxLKCs94xxV6KtSy9FVm4w2yPeEbYEtOTh7a5ASWNFz9Oas2aPihkLcKD0UmKlRHVWBUVSYjPHp8TRqIRZbedfXlnrQAnnqXtMQAdIs8a0qvDaZUkeXAKk8zJeyu5H05AU357gHGXAtZVbhvJ20ypHROAvFx1R82O41OE21AgMBAAECgYAbAww6maDjf53q1K5cL4f5WZdaWPSpv7PLmvsM/k8ogRAIunIJeCu1sdRztxp86XzezdemJM56mEkaUvtPtW+t4BLQuj9uaUw5uvYyWWKDRKIEK+UIoEyNOzsNHxzMe9UWd2fwUa8WzL82eMtfJsH39apTUrFV3mM7qSF54mARcQJBANp0VUPgPX8kPYekdbi0FR5eJiCZShWto6JImf0JS1EcQAIDoUwKRGVOumvvdiQrFP8uHp10fU9Y6SUH3mrPx7cCQQDDfVZCpxLv7Ipfcu1SKy1+YejveZA7ue3HjX86HrA86qB7vocBlzEmtncIubcA5QhhaauHy3Sb2DlyU0Gukh3zAkAEHrWM9imywCg46q0dsqfDTttBOiLfjcrMQLpGv2ogOXwrjY35NShdEMMLThTYUcevmFsTdSL34CFlhWR4dzq5AkEAkXwEp0P5lu6dqB06uw0BJW4uUZJRofFkIT+PsKxIEn22g4EuriNb4+ilO6wioprQmtZuXnguxxCq6AdH+WgquwJAJ7RRUkXM4k2wMLX5HHAPSLOGz9MXyb426olbDxGraBsLtelNcPYJo9r0zAwiYYzQMBl9D7xln131zvxqQa2Obg==';//PKCS8私钥
    public $private_key='MIICXAIBAAKBgQCm0ZFcSygrPeMcVeirUsvRVZuMNsj3hG2BLTk4e2uQEljRc/TmrNmj4oZC3Cg9FJipUR1VgVFUmIzx6fE0aiEWW3nX15Z60AJ56l7TEAHSLPGtKrw2mVJHlwCpPMyXsruR9OQFN+e4BxlwLWVW4bydtMqR0TgLxcdUfNjuNThNtQIDAQABAoGAGwMMOpmg43+d6tSuXC+H+VmXWlj0qb+zy5r7DP5PKIEQCLpyCXgrtbHUc7cafOl83s3XpiTOephJGlL7T7VvreAS0Lo/bmlMObr2Mllig0SiBCvlCKBMjTs7DR8czHvVFndn8FGvFsy/NnjLXybB9/WqU1KxVd5jO6kheeJgEXECQQDadFVD4D1/JD2HpHW4tBUeXiYgmUoVraOiSJn9CUtRHEACA6FMCkRlTrpr73YkKxT/Lh6ddH1PWOklB95qz8e3AkEAw31WQqcS7+yKX3LtUistfmHo73mQO7ntx41/Oh6wPOqge76HAZcxJrZ3CLm3AOUIYWmrh8t0m9g5clNBrpId8wJABB61jPYpssAoOOqtHbKnw07bQToi343KzEC6Rr9qIDl8K42N+TUoXRDDC04U2FHHr5hbE3Ui9+AhZYVkeHc6uQJBAJF8BKdD+ZbunagdOrsNASVuLlGSUaHxZCE/j7CsSBJ9toOBLq4jW+PopTusIqKa0JrWbl54LscQqugHR/loKrsCQCe0UVJFzOJNsDC1+RxwD0izhs/TF8m+NuqJWw8Rq2gbC7XpTXD2CaPa9MwMImGM0DAZfQ+8ZZ9d9c78akGtjm4=';//RSA私钥
    public $public_key='MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCm0ZFcSygrPeMcVeirUsvRVZuMNsj3hG2BLTk4e2uQEljRc/TmrNmj4oZC3Cg9FJipUR1VgVFUmIzx6fE0aiEWW3nX15Z60AJ56l7TEAHSLPGtKrw2mVJHlwCpPMyXsruR9OQFN+e4BxlwLWVW4bydtMqR0TgLxcdUfNjuNThNtQIDAQAB';//开发者公钥

    public function _initialize(){
        //$this->accesstoken=$this->GetAccessToken();
        $this->m=D('member');
        // $this->lang=(I('get.lang'))?I('get.lang'):'cn';
        // $this->config=C('lang_'.$this->lang);
        // $this->config['login_first'];
        // if($this->is_test)
        //     $this->mch_key=$this->mck_key_sanxbox;
    }
    /*获取token*/
    protected function GetAccessToken(){
        $token = M('baidu')->where(['id'=>1])->find();
        if(!empty($token) && $token['time']>time()){
            return $token['token'];
        }else{
            $token = $this->SetAccessToken();
            $save = M('baidu')->where(['id'=>1])->save(['token'=>$token,'time'=>time()+2590000]);
            return $token;
        }
    }
    /*设置token*/
    protected function SetAccessToken(){
    	$url ="https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=".$this->key."&client_secret=".$this->secret."&scope=smartapp_snsapi_base";
        $token=json_decode(get($url),true);
        return $token['access_token'];
    }
    /*百度小程序登录*/
    public function BaiduLogin($code){
        // $url = "https://spapi.baidu.com/oauth/jscode2sessionkey";
        // $url = "https://openapi.baidu.com/nalogin/getSessionKeyByCode";
        // $data = array(
        //     "code"=>$code,
        //     "client_id"=>'cLZaputiWn1Bgkom6XVgEIeO49HHLHjf',
        //     "sk" =>'IzY9h91EEfo4WPfAUVdgtCo1oTMRynQI'
        // );
        // ll($data);die;
        $res=get("https://spapi.baidu.com/oauth/jscode2sessionkey?code=".$code."&client_id=".$this->key."&sk=".$this->secret);
        // $res=$this->curlPost($url,$data);
        return $res;
    }
    /*百度小程序授权路程*/
    public function login(){
        $code = I('code','','string');
        if(empty($code))
            error($this->config['parr_err']);
        $data=json_decode($this->BaiduLogin($code),true);
        // ll($data);die;
        // var_dump($data);
        if($data['errno'])
            error_sys($data['error']);
        $userInfo=$this->m->where(['openid'=>$data['openid'],'from'=>'baidu'])->find();
        if(!empty($userInfo)){
            if(I('post.nickName')&&I('post.avatarUrl')) {
                $this->m->where(array('openid' => $data['openid'],'from'=>'baidu'))->save(array(
                    'nickname'  => I('post.nickName'),
                    'avatar'    => I('post.avatarUrl')
                ));
            }
        }else{
            $res = $this->m->add(array(
                'nickname'  => I('post.nickName'),
                'openid'    =>$data['openid'],
                'avatar'    => I('post.avatarUrl'),
                'from'      =>'baidu'
            ));
            $userInfo['id'] = $res;
        }
        success(array('token'=>$this->m->login($userInfo['id'],$userInfo['username'])),$this->config['success']);
    }

    //====================百度小程序支付weapon=========================
    public function pay($order_no){
        header("Content-Type: text/html;charset=utf-8");
        // $RSASign =new \Org\Util\RSASign();
        $order = M('order')->where(['order_no'=>$order_no])->find();//订单详情
        // success($order);die;
        $price = $order['advance_price']*100;
        $arr['appKey'] = $this->appKey;
        $arr['dealId'] = $this->dealId;
        $arr['tpOrderId'] = $order_no;
        $arr['totalAmount'] = $price;
        $arr['rsaSign'] = $this->genSignWithRsa($arr,$this->private_key);//获取签名
        // ll($arr);die;
        // $arr['rsaSign'] = $RSASign->sign($arr,$this->private_key);//获取签名
        // $order_id =1;//测试值
        $orderInfo ['dealId'] = $this->dealId;//跳转百度收银台支付必带参数之一
        $orderInfo ['appKey'] = $this->appKey;//支付能力开通后分配的支付 appKey
        $orderInfo ['totalAmount'] = $price;//订单金额 分为单位
        $orderInfo ['tpOrderId'] = $order_no;//项目订单号
        $orderInfo ['dealTitle'] = '北郡搬家订单';//订单名
        $orderInfo ['signFieldsRange'] = 0;//验签字段范围，：0：原验签字段 appKey+dealId+tpOrderId；1：包含 appKey+dealId+tpOrderId+totalAmount，固定值为 1
        $orderInfo ['rsaSign'] = $arr['rsaSign'];//签名
        $orderInfo ['bizInfo'] = $this->bizInfo($order_no,$arr['rsaSign'],$price);//订单的详细信息(非必填)
        // $this->ajaxReturn(['info'=>$orderInfo]);exit;
        return $orderInfo;
    }
    //拼接订单相关信息
    public function bizInfo($order_no,$rsaSign,$price){
        header("Content-Type: text/html;charset=utf-8");
        //查询订单详情后
        $bizInfo['tpData']['appKey']= $this->appKey;
        $bizInfo['tpData']['dealId']=$this->dealId;;
        $bizInfo['tpData']['tpOrderId']=$order_no;
        $bizInfo['tpData']['rsaSign']=$rsaSign;//签名
        $bizInfo['tpData']['totalAmount']=$price;
        $bizInfo['tpData']['returnData']=array('bizKey1'=>'字段值1','bizKey2'=>'字段2');
        // $bizInfo['tpData']['displayData']['cashierTopBlock']=array(
        //     '0'=>array(
        //         '0'=>array('leftCol'=>'订单名称','rightCol'=>'刘先生订单'),
        //         '1'=>array('leftCol'=>'数量','rightCol'=>'1'),
        //         '2'=>array('leftCol'=>'小计','rightCol'=>'300')
        //     ),
        //     '1'=>array(
        //         '0'=>array('leftCol'=>'地址','rightCol'=>'沈阳'),
        //         '1'=>array('leftCol'=>'时间','rightCol'=>date('Y-m-d H:i:s')),
        //         '2'=>array('leftCol'=>'人员','rightCol'=>'weapon')
        //     ),
        // );
        return json_encode($bizInfo,JSON_UNESCAPED_UNICODE);//无编码返回md
    }
    /**
     * 私钥生成签名字符串
     * @param array $assocArr
     * @param $priKey
     * @param bool $rsaPriKeyStr
     * @return string
     */
    private function genSignWithRsa(array $assocArr,$priKey, $rsaPriKeyStr = true){
        $sign = '';
        if (empty($rsaPriKeyStr) || empty($assocArr)) {
            return $sign;
        }
        $priKey = chunk_split($priKey, 64, "\n");
        $priKey = "-----BEGIN RSA PRIVATE KEY-----\n$priKey-----END RSA PRIVATE KEY-----\n";
        if (isset($assocArr['sign'])) {
            unset($assocArr['sign']);
        }
        ksort($assocArr); //按字母升序排序
        $parts = array();
        foreach ($assocArr as $k => $v) {
            $parts[] = $k . '=' . $v;
        }
        $str = implode('&', $parts);
        openssl_sign($str, $sign, $priKey);
        return base64_encode($sign);
    }


    //百度小程序支付回调
    public function payNotify(){
        $data =  $_POST;
        file_put_contents('baidu.txt',json_encode($data),FILE_APPEND);//追加写入消息日志
		///支付回调
        $userId     = $data['userId']; //百度用户ID
        $orderId    = $data['orderId']; //百度平台订单ID【幂等性标识参数】(用于重入判断)
        $unitPrice  = $data['unitPrice']; //单位：分
        $count      = $data['count']; //数量
        $totalMoney = $data['totalMoney']; //订单的实际金额，单位：分
        $payMoney   = $data['payMoney']; //扣除各种优惠后用户还需要支付的金额，单位：分
        $dealId     = $data['dealId']; //百度收银台的财务结算凭证
        $payTime    = $data['payTime']; //支付完成时间，时间戳
        $payType    = $data['payType']; //支付渠道值
        $partnerId  = $data['partnerId']; //支付平台标识值
        $status     = $data['status']; //1：未支付；2：已支付；-1：订单取消
        $tpOrderId  = $data['tpOrderId']; //业务方唯一订单号
        $returnData = $data['returnData']; //业务方下单时传入的数据
        $rsaSign    = $data['rsaSign']; //全部参数参与签名
        // file_put_contents('baidu.txt',json_encode($data),FILE_APPEND);//追加写入消息日志

        unset($data['rsaSign']); // rsaSign 不需要参与签名
        $data['sign'] = $rsaSign;
        $check_sign = $this->checkSignWithRsa($data);
        if ($check_sign){// 验签失败
            return 'failed';
        };

        if($status == 2) {
             // 如果订单已支付，进行业务处理并返回核销信息
            // file_put_contents('pay.txt','支付成功='.$tpOrderId,FILE_APPEND);//追加写入消息日志
            //根据返回的订单号做业务逻辑
            if(strpos($tpOrderId,'BJ') !== false){ 
                //预付款
                $arr = array(
                    'status' => 1,
                    'paytime'=>date('Y-m-d H:i:s'),
                    'orderId'=>$orderId,
                    'userId'=>$userId,
                    'pay_from'=>'baidu'
                );
                $re = M('order')->where(['order_no'=>$tpOrderId])->save($arr);
                $valuation_id = M('order')->where(['order_no'=>$tpOrderId])->getField('valuation_id');//意向记录id
                if(!empty($valuation_id)){
            		M('order_valuation')->where(['id'=>$valuation_id])->delete();//订单已支付，删除意向记录
                }
            }else{
                $arr = array(
                    'status' => 4,
                );
                $re = M('order')->where(['order_no_small'=>$tpOrderId])->save($arr);
            }
            // 需要返回的响应
            $ret['errno'] = 0;
            $ret['msg']   = 'success';
            $ret['data']  = array('isConsumed'=>2);
            echo json_encode($ret);exit;
        }

     }

     /**
      * 公钥校验签名
      * @param array $assocArr
      * @param bool $rsaPubKeyStr
      * @return bool
      */
     private function checkSignWithRsa(array $assocArr ,$rsaPubKeyStr = true){
         if (!isset($assocArr['sign']) || empty($assocArr) || empty($rsaPubKeyStr)) {
             return false;
         }

         $sign = $assocArr['sign'];
         unset($assocArr['sign']);

         if (empty($assocArr)) {
             return false;
         }

         ksort($assocArr); //按字母升序排序
         $parts = array();
         foreach ($assocArr as $k => $v) {
             $parts[] = $k . '=' . $v;
         }
         $str    = implode('&', $parts);
         $sign   = base64_decode($sign);
         $pubKey = 'bd_pub_key';  // 公钥串
         $pubKey = chunk_split($pubKey, 64, "\n");
         $pubKey = "-----BEGIN PUBLIC KEY-----\n$pubKey-----END PUBLIC KEY-----\n";
         $result = (bool)openssl_verify($str, $sign,$pubKey);
         return $result;
     }
     //退款
     public function refund($baidu){
     	$url='https://openapi.baidu.com/rest/2.0/smartapp/pay/paymentservice/applyOrderRefund';//退款2.0接口
     	$baidu['access_token'] = $this->GetAccessToken();
     	$res = $this->send_post($url,$baidu);
     	$arr = json_decode($res,true);
     	return $arr;//返回退款结果
     }

 	public function send_post($url, $data) {
	   //初使化init方法
	   $ch = curl_init();
	   //指定URL
	   curl_setopt($ch, CURLOPT_URL, $url);
	   //设定请求后返回结果
	   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	   //声明使用POST方式来进行发送
	   curl_setopt($ch, CURLOPT_POST, 1);
	   //发送什么数据呢
	   curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	   //忽略证书
	   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	   //忽略header头信息
	   curl_setopt($ch, CURLOPT_HEADER, 0);
	   //设置超时时间
	   curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	   //发送请求
	   $output = curl_exec($ch);
	   //关闭curl
	   curl_close($ch);
	   //返回数据
	   return $output;
	}
}